from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import re

db = SQLAlchemy()

# 预定义的用户白名单
VALID_USERS = [
    ("申倩", "女"),
    ("毕盛楠", "女"),
    ("梁熙", "男"),
    ("王莉", "女"),
    ("王雪", "女"),
    ("张屹华", "女"),
    ("包东杰", "男"),
    ("白哈达", "男"),
    ("付海生", "男"),
    ("格格塔娜", "女"),
    ("关格日乐吐", "男"),
    ("和少勇", "男"),
    ("化姝宁", "女"),
    ("贾志刚", "男"),
    ("刘剑", "男"),
    ("刘维", "男"),
    ("刘伟", "男"),
    ("刘钊", "男"),
    ("孟朴钊", "男"),
    ("平杰", "男"),
    ("钱尚毅", "男"),
    ("任鑫", "男"),
    ("苏日嘎拉图", "男"),
    ("王邦", "男"),
    ("王麒然", "男"),
    ("谢飞", "男"),
    ("赵勇", "男")
]

# 奖号池
LOTTERY_NUMBERS = [
    "016199", "016200", "016201", "016202", "016203", "016204", "016205",
    "016206", "016207", "016208", "016209", "016210", "016211", "016212",
    "016213", "016214", "016215", "016216", "016217", "016218", "016219",
    "016220", "016221", "016222", "016223", "016224", "016225"
]

class LotterySettings(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    is_active = db.Column(db.Boolean, default=False)
    round_number = db.Column(db.Integer, default=1)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

class LotteryResult(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    gender = db.Column(db.String(10), nullable=False)
    id_card = db.Column(db.String(18), nullable=False)
    level = db.Column(db.String(50), nullable=False)
    lottery_number = db.Column(db.String(10), nullable=False)
    round_number = db.Column(db.Integer, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

def validate_id_card(id_card):
    """验证身份证格式"""
    # 18位身份证号码的正则表达式
    pattern = r'^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$'
    return bool(re.match(pattern, id_card))

def validate_user(name, gender):
    """验证用户是否在白名单中"""
    return (name, gender) in VALID_USERS

def get_available_numbers(round_number):
    """获取当前轮次可用的号码"""
    used_numbers = db.session.query(LotteryResult.lottery_number).filter_by(round_number=round_number).all()
    used_numbers = [num[0] for num in used_numbers]
    available = [num for num in LOTTERY_NUMBERS if num not in used_numbers]
    return available

def user_already_participated(name, round_number):
    """检查用户是否已经参与了当前轮次的抽奖"""
    result = LotteryResult.query.filter_by(name=name, round_number=round_number).first()
    return result is not None
